import Vue from 'vue'
import App from './App.vue'

import myconfig from './utils/myconfig'

import VueRouter from 'vue-router'
import router from './router'
import axios from 'axios'

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
// import CKEditor from '@ckeditor/ckeditor5-vue2'
// //引入中文
// import '@ckeditor/ckeditor5-build-classic/build/translations/zh-cn.js'

// Vue.use(CKEditor)
Vue.use(ElementUI)
Vue.use(VueRouter)

Vue.config.productionTip = false

//前置拦截器
axios.interceptors.request.use(config=>{
  // console.log(sessionStorage.getItem('token'))
  if(sessionStorage.getItem('token')!=null){
    config.headers.Authorization=JSON.parse(sessionStorage.getItem('token')).token
  }else{
    config.headers.Authorization=''
  }
  return config
})

//后置拦截器
axios.interceptors.response.use(rs=>{
  if(rs.data.code === 5420){
    sessionStorage.clear()
    myvue.$message.error('请登录再操作！')
    myvue.$bus.$emit('adminLogin',2)
    router.replace({name:'index-main'},()=>{})
  }
  return rs
})

Vue.prototype.$axios = axios
Vue.prototype.myconfig = myconfig

//前置路由守卫
router.beforeEach((to,form,next)=>{
  if(Object.keys(to.meta).length === 0){
      next()
  }else{
    
      let userPermission = sessionStorage.getItem('token') == null ? 0 : JSON.parse(sessionStorage.getItem('token')).user.utype
      let flag = false
      
      to.meta.permissions.forEach(p=>{
        if(userPermission === p){
          flag = true
          return
        }
      })

      if(flag){
          next()
      }else{
        myvue.$bus.$emit('adminLogin',2)
        myvue.$message.error('无权访问')
      }
  } 
})

let myvue = new Vue({
  render: h => h(App),
  router,
  beforeCreate(){
    Vue.prototype.$bus=this
  }
}).$mount('#app')

console.log(myvue)
